<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input
          v-model.trim="form.exchange"
          class="!w-[160px]"
          placeholder="交换机名称"
          clearable
        ></el-input>
        <el-input
          v-model.trim="form.routing_key"
          class="!w-[160px]"
          placeholder="路由键"
          clearable
        ></el-input>
        <el-input
          v-model.trim="form.payload"
          class="!w-[160px]"
          placeholder="载荷"
          clearable
        ></el-input>
        <el-select class="!w-[160px]" v-model="form.processing_status" placeholder="状态">
          <el-option
            v-for="item in options['base.ExceptionMsg']?.[0].processingStatusText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <VGroup>
          <el-select class="!w-[160px]" v-model="form.timeRange.type">
            <el-option
              v-for="item in timeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.timeRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 300px"
            :default-time="defaultTime()"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-button :loading="loadings.enable" @click="handleProcessed()"
          >标记已处理</el-button
        >
      </template>
    </VTable>
  </VPage>
</template>
<script setup lang="jsx" name="BasicsException-msg">
import { ElMessage, ElMessageBox } from "element-plus";
import { queryException, processed, retry } from "./api";
import { getOptions } from "@/api/index.js";

const tableRef = ref();
const timeOption = [
  { label: "创建时间", value: "create_time" },
  { label: "错误时间", value: "error_at" },
];

// 枚举类
let options = ref([]);
const fetchOption = () => {
  getOptions({
    name: ["base.ExceptionMsg"],
  }).then((res) => {
    options.value = res.data;
  });
};
onMounted(() => {
  fetchOption();
});

const loadings = reactive({
  enable: false,
  disable: false,
  del: false,
});
const tableOptins = reactive({
  formConfig: {
    data: {
      timeRange: { type: "create_time", value: [], range: true },
    },
  },
  rowConfig: {
    height: 52,
  },
  columns: [
    { type: "checkbox", width: 50 },
    { field: "id", title: "ID", width: 50 },
    { field: "exchange", title: "交换机" },
    { field: "routing_key", title: "路由键" },
    { field: "retry_times", title: "重试次数" },
    { field: "consumer_class", title: "消费执行类" },
    { field: "payload", title: "载荷" },
    { field: "error_msg", title: "错误消息" },
    { field: "create_user", title: "创建人" },
    { field: "processing_status_text", title: "处理状态" },
    { field: "error_at", title: "错误时间" },
    {
      title: "操作",
      fixed: "right",
      width: 80,
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex">
              {row.processing_status == 0 && (
                <el-button link type="primary" onClick={() => handleRetry(row.id)}>
                  重试
                </el-button>
              )}
            </div>
          );
        },
      },
    },
  ],

  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => queryException({ ...form, ...page }),
    },
  },
});

onMounted(() => {});
const query = () => {
  tableRef?.value.query();
};
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};
const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};

const handleProcessed = () => {
  if (!isHandle()) return;
  const records = getSelectRow().map((i) => i.id);
  ElMessageBox.confirm("是否将勾选项标记为已处理?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loadings.del = true;
    processed({ ids: records })
      .then((res) => {
        query();
        ElMessage.success(res.message);
      })
      .finally(() => {
        loadings.del = false;
      });
  });
};

const handleRetry = async (id) => {
  try {
    const res = await retry({ id });
    query();
    ElMessage.success(res.message);
  } catch (e) {
    throw Error(e);
  }
};
</script>
